<?php
namespace backend\controllers;
use backend\models\AgentAreaModel;
use backend\models\ExcelModel;
use Yii;
use backend\base\BaseController;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use backend\models\UserModel;
use backend\models\AreaModel;
use backend\base\BaseService;

/**
 * 用户管理
 * Class UserController
 * @package backend\controllers
 */
class UserController extends BaseController
{
    /**
     * 学生列表
     */
    public function actionList(){
        $export = Yii::$app->request->get('export','');
        $keyword = Yii::$app->request->get('keyword','');
        $registered_from = Yii::$app->request->get('registered_from','');
        $is_delete = Yii::$app->request->get('is_delete','');
        $input_date = Yii::$app->request->get('input_date','');
        $agent_id = Yii::$app->request->get('agent_id','');
        $_area = Yii::$app->request->get('_area');
        $province = isset($_area['province']) && $_area['province'] ? $_area['province'] : null;
        $city = isset($_area['city']) && $_area['city'] ? $_area['city'] : null;
        $country = isset($_area['country']) && $_area['country'] ? $_area['country'] : null;

        $query = UserModel::find();
        $query->andWhere(['is_delete'=>$is_delete?1:0]);
        if(is_numeric($keyword)&& strlen($keyword) < 11){
            $query->andFilterWhere(['id'=>$keyword]);
        }else{
            $query->andFilterWhere(['or',['like', 'telephone', $keyword],['like', 'nickname', $keyword]]);
        }
        $query->andFilterWhere(['registered_from'=>$registered_from]);
        $query->andFilterWhere(['province'=>$province]);
        $query->andFilterWhere(['city'=>$city]);
        $query->andFilterWhere(['country'=>$country]);
        if($input_date){
            $input_date_arr = explode('~',$input_date);
            $query->andFilterWhere(['between','create_time',strtotime($input_date_arr[0]),strtotime($input_date_arr[1])]);
        }
        if($agent_id){
            $country = AgentAreaModel::getAgentCountry($agent_id);
            $query->andFilterWhere(['in','country',$country]);
        }
        //导出
        if($export){
            ExcelModel::userExport($query);
            return '';
        }
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 15,
            ],
            'sort' => [
                'attributes'=>['id'],
                'defaultOrder' => [
                    'id' => SORT_DESC,
                ]
            ],
        ]);
        $area = new AreaModel();
        $area_select = $area->getAreaSelect($province, $city, $country);
        return $this->render('list',[
            'keyword'=>$keyword,
            'registered_from'=>$registered_from,
            'is_delete'=>$is_delete,
            'agent_id'=>$agent_id,
            'input_date'=>$input_date,
            'registered_from_arr'=>UserModel::$registered_from_arr,
            'area'=> $area,
            'area_select'=> $area_select,
            'dataProvider'=>$dataProvider
        ]);
    }

    /**
     * 编辑
     * @return string
     */
    public function actionEdit($id)
    {
        $model = UserModel::findOne($id);
        if(Yii::$app->request->isPost){
            $model->setScenario('edit');
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                $this->addRecord('编辑学生',$id);
                return $this->saveBack(['list']);
            }
        }
        //获取关联地区
        $area_select = (new AreaModel)->getAreaSelect($model->province,$model->city,$model->country);
        return $this->render('edit',['model'=>$model,'id'=>$id,'area_select'=>$area_select]);
    }

    /**
     * 用户详情
     */
    public function actionDetail($id)
    {
        $id=(int)$id;
        $user = UserModel::findOne($id);
        $area = implode('、',(new AreaModel)->getAreaName([$user->province,$user->city,$user->country]));
        $this->layout = false;
        $info = UserModel::otherDetail($user);
        return $this->render('detail',['user'=>$user,'info'=>$info,'id'=>$id,'area'=>$area]);
    }

    /**
     * 删除
     * @return string
     */
    public function actionDeleAjaxDo()
    {
        $data = $this->body;
        $model = UserModel::findOne(intval($data['id']));
        if($model){
            $is_delete = isset($data['delete']) ? $data['delete'] : 1;
            $model->is_delete = $is_delete;
            if($model->save()){
                $this->addRecord('删除学生',$data['id']);
                return json_encode(parent::ajaxReturn('operate_success', []));
            }
        }
        return json_encode(parent::ajaxReturn('operate_error_delete', []));
    }

    /**
     * 修改状态,禁用|解禁
     */
    public function actionStatusAjaxDo()
    {
        $data = $this->body;
        $model = UserModel::findOne(intval($data['id']));
        if($model){
            if(UserModel::updateAll(['status'=>intval($data['status'])],['id'=>intval($data['id'])])){
                $this->addRecord('禁用|解禁学生',$data['id']);
                return json_encode(parent::ajaxReturn('operate_success', []));
            }
        }
        return json_encode(parent::ajaxReturn('edit_error', []));
    }


    /**
     * VIP列表
     */
    public function actionVipList(){
        $keyword = Yii::$app->request->get('keyword','');
        $vip = Yii::$app->request->get('vip');

        $query = UserModel::find();
        $query->andWhere(['is_delete'=>0,'status'=>0]);
        if(is_numeric($keyword)&& strlen($keyword) < 11){
            $query->andFilterWhere(['id'=>$keyword]);
        }else{
            $query->andFilterWhere(['or',['like', 'telephone', $keyword],['like', 'nickname', $keyword]]);
        }
        $query->andFilterWhere(['vip'=>$vip]);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 15,
            ],
            'sort' => [
                'attributes'=>['id'],
                'defaultOrder' => [
                    'id' => SORT_DESC,
                ]
            ],
        ]);
        return $this->render('vip-list',[
            'keyword'=>$keyword,
            'vip'=>$vip,
            'dataProvider'=>$dataProvider
        ]);
    }


    /**
     * VIP 设置|取消
     */
    public function actionVipAjaxDo()
    {
        $data = $this->body;
        $model = UserModel::findOne(intval($data['id']));
        if($model){
            if(UserModel::updateAll(['vip'=>$data['vip'] == 1 ? 1:0],['id'=>intval($data['id'])])){
                $this->addRecord('设置|取消VIP',$data['id']);
                return json_encode(parent::ajaxReturn('operate_success', []));
            }
        }
        return json_encode(parent::ajaxReturn('edit_error', []));
    }

    /**
     * 搜索学生列表
     * @return string
     * @throws \yii\base\Exception
     */
    public function actionSearchListAjaxDo()
    {
        $list = [];
        $keywords = Yii::$app->request->post('keywords','');
        $user_id = Yii::$app->request->post('user_id','');
        $telephone = Yii::$app->request->post('telephone','');
        $query = UserModel::find()->select('id,nickname,status,telephone,is_delete,create_time');
        if(!empty($keywords)){
            if(is_numeric($keywords)){
                $query->andWhere(['id'=>$keywords]);
            }else{
                $query->andWhere(['like','nickname',$keywords]);
            }
        }elseif(!empty($user_id)){
            $query->andWhere(['id'=>$user_id]);
        }elseif(!empty($telephone)){
            $query->andWhere(['telephone'=>$telephone]);
        }
        $list = $query->limit(200)->orderBy('id desc')->asArray()->all();
        if($list){
            foreach($list as $key=>$val){
                $list[$key]['status_name'] = $val['is_delete'] == 1 ? '已删除':($val['status'] == 1 ?'已禁用':'正常');
                $list[$key]['create_time'] = date('Y-m-d H:i',$val['create_time']);
            }
        }
        return json_encode(parent::ajaxReturn('operate_success', $list));
    }
}

?>